package wn.lizzy.essay.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.common.base.Strings;

import wn.lizzy.essay.config.CustomAuthenticationProvider;
import wn.lizzy.essay.entity.Text;
import wn.lizzy.essay.entity.User;
import wn.lizzy.essay.service.ClassificationService;
import wn.lizzy.essay.service.TextService;
import wn.lizzy.essay.service.TypeService;

@Controller
@RequestMapping("/essay")
public class TextController {
	private static final Logger logger = LoggerFactory.getLogger(TextController.class);
	@Resource
	private Environment env;
	@Resource
	private TextService textService;
	@Resource
	private ClassificationService classificationService;
	@Resource
	private TypeService typeService;
	/**
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/textmanage/{valid}", method = RequestMethod.GET)
	public Callable<String> textManage(@PathVariable("valid") int valid,String pageNo,Model model) {
		return () -> {
			logger.trace("essay/text/manage");
			int PAGE_SIZE = Integer.parseInt(env.getProperty("essay.basic.pageinfo"));
			Map<String,Object> queryPrams = new HashMap<String,Object>();
			queryPrams.put("valid", valid);
			Page<Text> datas =  textService.getTextList(queryPrams, new PageRequest(0, PAGE_SIZE));
			Long itemsCount = datas.getTotalElements();
			
			model.addAttribute("types", typeService.getTypes());
			model.addAttribute("valid", valid);
			model.addAttribute("pageNo", 1);
			model.addAttribute("pageSize", PAGE_SIZE);
			model.addAttribute("itemsCount", itemsCount);
			model.addAttribute("text_datas", datas.getContent());
			return "essay/text/manage";
		};
	}
	
	@RequestMapping(value = "/textManagePage", method = RequestMethod.POST)
	public Callable<String> textManagePage(int valid,String title,String stime,String etime,int pageNo,Model model) {
		return () -> {
			logger.trace("essay/text/managepage");
			int PAGE_SIZE = Integer.parseInt(env.getProperty("essay.basic.pageinfo"));
			Map<String,Object> queryPrams = new HashMap<String,Object>();
			queryPrams.put("valid", valid);
			try{
				if(!Strings.isNullOrEmpty(title))
					queryPrams.put("title", title);
				if(!Strings.isNullOrEmpty(stime)){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					queryPrams.put("stime", sdf.parse(stime));
				}
				if(!Strings.isNullOrEmpty(etime)){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					queryPrams.put("etime", sdf.parse(etime));
				}
			}catch (ParseException e) {
				e.printStackTrace();
			}
			Page<Text> datas =  textService.getTextList(queryPrams, new PageRequest(pageNo-1, PAGE_SIZE));
			Long itemsCount = datas.getTotalElements();
			
			model.addAttribute("valid", valid);
			model.addAttribute("types", typeService.getTypes());
			model.addAttribute("pageNo", pageNo);
			model.addAttribute("pageSize", PAGE_SIZE);
			model.addAttribute("itemsCount", itemsCount);
			model.addAttribute("text_datas", datas.getContent());
			return "essay/text/manage";
		};
	}
	
	@RequestMapping(value = "/textadd/{valid}/{typeid}", method = RequestMethod.GET)
	public Callable<String> textAdd(@PathVariable("valid") int valid,@PathVariable("typeid") Long typeid, Model model) {
		return () -> {
			logger.trace("essay/text/textadd");
			model.addAttribute("classificationList",classificationService.getClassification());
			model.addAttribute("valid", valid);
			model.addAttribute("typeid", typeid);
			return "essay/text/add";
		};
	}
	
	@RequestMapping(value = "/textupdate/{uid}/{valid}", method = RequestMethod.GET)
	public Callable<String> textUpdate(@PathVariable("uid") Long uid,@PathVariable("valid") int valid, Model model) {
		return () -> {
			logger.trace("essay/text/textupdate");
			model.addAttribute("classificationList",classificationService.getClassification());
			model.addAttribute("text",textService.getText(uid));
			model.addAttribute("uid", uid);
			model.addAttribute("valid", valid);
			return "essay/text/update";
		};
	}
	
	@RequestMapping(value = "/textsave", method = RequestMethod.POST)
	public Callable<String> textsave(int valid,Text text, Long classid, Long typeid,Model model) {
		return () -> {
			User principal = CustomAuthenticationProvider.getUserInfo();
			textService.saveText(principal, text, classid, typeid);
			return "redirect:/essay/textmanage/"+valid+"";
		};
	}
	
	@RequestMapping(value = "/textupdate", method = RequestMethod.POST)
	public Callable<String> textupdate(Long uid,int valid ,Text text, Long classid,Model model) {
		return () -> {
			User principal = CustomAuthenticationProvider.getUserInfo();
			textService.updateText(principal, uid, text,classid);
			return "redirect:/essay/textmanage/"+valid+"";
		};
	}
	
	@RequestMapping(value = "/textdelete/{uid}/{valid}", method = RequestMethod.GET)
	public Callable<String> textdelete(@PathVariable("uid") Long uid,@PathVariable("valid") int valid ,Model model) {
		return () -> {
			if(valid == 0) textService.deleteText(uid); //草稿直接删除
			else {
				User principal = CustomAuthenticationProvider.getUserInfo();
				textService.updateValid(principal,uid, 0);
			}
			return "redirect:/essay/textmanage/"+valid+"";
		};
	}
	
	@RequestMapping(value = "/textpublish/{uid}/{valid}", method = RequestMethod.GET)
	public Callable<String> textpublish(@PathVariable("uid") Long uid,@PathVariable("valid") int valid ,Model model) {
		return () -> {
			User principal = CustomAuthenticationProvider.getUserInfo();
			textService.updateValid(principal,uid, 1);
			return "redirect:/essay/textmanage/"+valid+"";
		};
	}
	
	@RequestMapping(value = "/textview/{uid}", method = RequestMethod.GET)
	public Callable<String> textview(@PathVariable("uid") Long uid ,Model model) {
		return () -> {
			model.addAttribute("text", textService.getText(uid));
			return "essay/text/view";
		};
	}
}
